const AUTH = require('../../../utils/auth')
import {
  updateUserInfo
} from "../../../api/miniProgramController";
import {
  mpId
} from "../../../utils/config";
import {
  Logs
} from "../../../utils/log";
const logs = new Logs();

import {
  getShopCartList,
  updateShopCartById,
  deleteShopCartById
} from "../../../api/shopCartController";
import {
  repurchasePlaceOrder
} from "../../../api/tradeOrderController";
import {
  wxJSAPIPayOrder
} from "../../../api/wxPayController";
import {
  orderTakingTmplIds
} from "../../../utils/config";
Component({
  properties: {
    addressInfo: { //地址信息
      type: Object,
      value: {
        contact: ''
      },
    },
    wxlogin: { // 注册成功 首页用来拦截
      type: Boolean,
      value: true
    }
  },
  options: {
    addGlobalClass: true,
  },
  /**
   * 页面的初始数据
   */
  data: {
    wxlogin: true,
    money: 0, //总价

    shopList: [], //  购物车列表
    allChecked: true, //全选
  },
  attached() {

    this.getShopCartList()
    this.allCheckboxChange()

    /**
     * 如果有custId 注册关于过 wxlogin 为true
     */
    // let custId = wx.getStorageSync('custId')
    // console.log(custId);
    // if (custId) {
    //   this.setData({
    //     wxlogin: true
    //   })
    // }else{
    //   this.setData({
    //     wxlogin: false
    //   })
    // }

  },
  methods: {
    // ListTouch触摸开始
    ListTouchStart(e) {
      this.setData({
        ListTouchStart: e.touches[0].pageX
      })
    },

    // ListTouch计算方向
    ListTouchMove(e) {
      this.setData({
        ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
      })
    },

    // ListTouch计算滚动
    ListTouchEnd(e) {
      if (this.data.ListTouchDirection == 'left') {
        this.setData({
          modalName: e.currentTarget.dataset.target
        })
      } else {
        this.setData({
          modalName: null
        })
      }
      this.setData({
        ListTouchDirection: null
      })
    },
    /**
     * 根据Id删除购物车
     */
    async deleteShopCartById(e) {
      let {
        id
      } = e.currentTarget.dataset
      let resolve = await deleteShopCartById({
        cartId: id
      })
      if (resolve.success) {
        wx.showToast({
          title: '删除成功！',
          success: () => {
            setTimeout(() => {
              this.getShopCartList()
            }, 1000);
          }
        })
      }

    },
    /**
     * 购物车列表
     */
    async getShopCartList() {
      let resolve = await getShopCartList({
        custId: wx.getStorageSync('custId'),
      })
      this.setData({
        shopList: resolve.data.list
      })
    },
    /**
     * 支付失败后查询列表
     */
    async getShopCartList2() {
      let resolve = await getShopCartList({
        custId: wx.getStorageSync('custId'),
      })
      this.setData({
        shopList: resolve.data.list,
        allChecked: false
      })
      this.getMoney()
    },
    /**
     * 触底
     */
    ScrollLower() {
      const self = this;

    },
    /**
     * 关闭弹窗
     */
    afterAuth(e) {
      console.log(e);
      this.setData({
        wxlogin: true,
        custId: ''
      })
    },
    /**
     * 检测是否注册 进入地址页面
     */
    openAddress() {
      let self = this
      AUTH.checkHasLogined().then(isCustId => {
        console.log('是否登录', isCustId);
        if (!isCustId) {
          self.setData({
            custId: '',
            wxlogin: false
          })
        } else {
          wx.navigateTo({
            url: '/pages/distributionCenter/address/index',
          })
        }
      })
    },
    /**
     * 处理加减法
     */
    handleNum(e) {
      let {
        type,
        id,
        index
      } = e.currentTarget.dataset
      // 减法 (不为0)
      if (type === 'del') {
        if (this.data.shopList[index].count <= 1) {
          return
        }
        this.data.shopList[index].count--
        this.setData({
          ['shopList[' + index + '].count']: this.data.shopList[index].count
        })
        this.updateShopCartById(id, this.data.shopList[index].count)
      } else if (type === 'add') {
        // 加法 (需要大于库存)
        this.data.shopList[index].count++
        this.setData({
          ['shopList[' + index + '].count']: this.data.shopList[index].count
        })
        // if (this.data.count>=库存) {
        //   return
        // }
        this.updateShopCartById(id, this.data.shopList[index].count)
      } else {
        let value = this.validateNumber(e.detail.value) - 0
        this.setData({
          ['shopList[' + index + '].count']: value
        })
        this.updateShopCartById(id, this.data.shopList[index].count)
      }
      this.getMoney()
    },
    /**
     * 根据Id修改购物车
     */
    async updateShopCartById(id, count) {
      let resolve = await updateShopCartById({
        id: id,
        count: count
      })
    },
    /**
     * 失去焦点
     */
    bindblur(e) {
      let {
        type,
        id,
        index
      } = e.currentTarget.dataset
      let value = this.validateNumber(e.detail.value) - 0
      value = value == 0 ? 1 : value
      this.setData({
        ['shopList[' + index + '].count']: value
      })
      this.updateShopCartById(id, value)
      this.getMoney()
    },
    validateNumber(val) {
      return val.replace(/\D/g, '')
    },
    /**
     * 单选
     */
    checkboxChange(e) {
      let {
        index
      } = e.currentTarget.dataset
      this.setData({
        ['shopList[' + index + '].checked']: !this.data.shopList[index].checked
      })
      this.getMoney()

      let list = this.data.shopList
      for (let i = 0; i < list.length; i++) {
        if (list[i].checked == false) {
          this.setData({
            allChecked: false
          })
          return
        }
      }
      this.setData({
        allChecked: true
      })
    },
    /**
     * 全选
     */
    allCheckboxChange() {
      this.setData({
        allChecked: !this.data.allChecked
      })
      let list = this.data.shopList
      for (let i = 0; i < list.length; i++) {
        this.setData({
          ['shopList[' + i + '].checked']: this.data.allChecked
        })
      }
      this.getMoney()
    },
    /**
     * 支付获取的id
     */
    shopCartIdList() {
      let payId = []
      let list = this.data.shopList
      list.map((item, index) => {
        if (item.checked) {
          payId.push(item.id)
        }
      })
      return payId
    },
    mock() {
      console.log('mock');
    },
    /**
     * 支付
     */
    wxPay() {
      let self = this


          // 校验是否有收货地址
          if (!self.data.addressInfo) {
            wx.showToast({
              title: '请选择收货地址',
              icon: 'none'
            })
            return
          }

          // 校验是否选中商品
          let list = self.data.shopList
          let isHaveChecked = false
          for (let i = 0; i < list.length; i++) {
            if (list[i].checked) {
              isHaveChecked = true
            }
          }
          if (!isHaveChecked) {
            wx.showToast({
              title: '请勾选商品！',
              icon: 'none'
            })
            return
          }
      wx.requestSubscribeMessage({
        tmplIds: orderTakingTmplIds,
        complete: (res) => {
          AUTH.checkHasLogined().then(isCustId => {
            if (!isCustId) {
              self.setData({
                custId: ''
              })
            } else {
              self.repurchasePlaceOrder()
            }
          })
        }
      })

    },
    /**
     * 复购产品下订单
     */
    async repurchasePlaceOrder() {
      let self = this
      let shopCartIdList = self.shopCartIdList()
      let custAddressId = self.data.addressInfo.id
      let resolve = await repurchasePlaceOrder({
        shopCartIdList: shopCartIdList,
        custAddressId: custAddressId
      })
      // 支付
      if (resolve.success) {
        self.wxJSAPIPayOrder(resolve.data)
      }

    },
    /**
     * 封装预下单方法
     */
    async wxJSAPIPayOrder(params) {
      let self = this
      let resolve = await wxJSAPIPayOrder({
        totalFee: self.data.money * 100,
        productDesc: '云上漂支付测试',
        wxPayOutTradeNo: params.wxPayOutTradeNo,
        tradeOrderId: params.id,
        userLoginState: wx.getStorageSync('userLoginState')
      })
      console.log('-----------封装预下单方法----------------');
      console.log(resolve);
      setTimeout(() => {
        self.getShopCartList2()
      }, 1500);
    },
    /**
     * 计算价格
     */
    getMoney() {
      console.log('----------商品----------', this.data.shopList);
      let money = 0
      let list = this.data.shopList
      for (let i = 0; i < list.length; i++) {
        let everyone = list[i]
        console.log(everyone);
        if (everyone.checked) {
          money += everyone.count * everyone.price
        }
      }
      this.setData({
        money: money
      })
    }
  },
  /**
   * 更新头像昵称
   */
  async updateUserInfo(res) {
    console.log('更新头像昵称');
    console.log(res);
    let resolve = await updateUserInfo({
      res: JSON.stringify(res),
      mpId: mpId
    })
    if (resolve.success) {
      console.log('userInfo');
      console.log(resolve);
      wx.setStorageSync('userInfo', resolve.data)
    }
  },
})